package com.jindu.producer.system.controller;

import com.jindu.kernel.page.AlphaPage;
import com.jindu.kernel.result.JsonResult;
import com.jindu.kernel.utils.AlphaBeanUtils;
import com.jindu.kernel.utils.DateUtils;
import com.jindu.kernel.utils.IdGenerator;
import com.jindu.producer.system.jpa.MenuJpa;
import com.jindu.producer.system.model.SMenuEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jarvis
 * @date 2018/2/21
 */
@Api(description = "菜单信息管理", tags = "MenuController", basePath = "/menu")
@RestController
@RequestMapping(value = "/menu",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class MenuController {

    @Autowired
    MenuJpa menuJpa;

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据菜单ID，查询菜单的详细信息", notes = "返回单个菜单的信息,菜单详细信息")
    @RequestMapping(value = "get",method = RequestMethod.GET)
    public JsonResult<SMenuEntity> get(@RequestParam String id){
        return JsonResult.getSuccessResult(menuJpa.findById(id));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据菜单父级ID，查询该parentId的子菜单列表", notes = "返回parentId的子菜单列表信息")
    @RequestMapping(value = "getByParentId",method = RequestMethod.GET)
    public JsonResult<List<SMenuEntity>> getByParentId(@RequestParam String parentId){
        return JsonResult.getSuccessResult(menuJpa.findAllByParentId(parentId));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "查询出菜单树，查询菜单的树形列表", notes = "返回菜单树形列表信息")
    @RequestMapping(value = "getMenuTree",method = RequestMethod.GET)
    public JsonResult<List<SMenuEntity>> getMenuTree(){

        List<SMenuEntity> menuEntities=menuJpa.findAll();
        List<SMenuEntity> sMenuTreeEntity=new ArrayList<>();

        List<SMenuEntity> root =menuEntities.stream()
                .filter(s -> s.getParentId().equals("0"))
                .collect(Collectors.toList());

        for (SMenuEntity menu : root){
            List<SMenuEntity> subNode=menuEntities.stream()
                    .filter(s->s.getParentId().equals(menu.getId()))
                    .collect(Collectors.toList());
            menu.setSubNode(subNode);

            sMenuTreeEntity.add(menu);
        }
        return JsonResult.getSuccessResult(sMenuTreeEntity);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "根据菜单ID，查询菜单的详细信息", notes = "返回单个菜单的信息,菜单详细信息")
    @RequestMapping(value = "getAll",method = RequestMethod.GET)
    public JsonResult<AlphaPage<SMenuEntity>> getAll(@RequestParam(value = "pageNo",defaultValue = "0") Integer pageNo,
                                                       @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
                                                       @RequestParam(value = "name", required = false) String name){

        Specification querySpecifi = (Specification<SMenuEntity>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if(name != null){
                predicates.add(criteriaBuilder.like(root.get("name"),"%"+name+"%"));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Page<SMenuEntity> entities=menuJpa.findAll(querySpecifi,new PageRequest(pageNo, pageSize));

        return new AlphaPage<>(entities).toJsonResult();
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "保存菜单的信息", notes = "保存菜单的信息")
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public JsonResult<SMenuEntity> save(@RequestBody SMenuEntity menuEntity){

        SMenuEntity sMenuEntity=menuJpa.findById(menuEntity.getId());
        if(sMenuEntity==null){
            menuEntity.setId(IdGenerator.uuid());
            menuEntity.setCreateTime(new Timestamp(DateUtils.getCurrentTime()));
            menuEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            return JsonResult.getSuccessResult(menuJpa.saveAndFlush(menuEntity));
        }else {
            menuEntity.setModifyTime(new Timestamp(DateUtils.getCurrentTime()));
            BeanUtils.copyProperties(menuEntity,sMenuEntity, AlphaBeanUtils.getNullPropertyNames(menuEntity));
            return JsonResult.getSuccessResult(menuJpa.saveAndFlush(sMenuEntity));
        }
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "token" , required = true, dataType = "String", paramType = "header")
    })
    @ApiOperation(value = "删除菜单的信息", notes = "根据菜单的ID,删除数据")
    @RequestMapping(value = "delete",method = RequestMethod.POST)
    public JsonResult<Integer> delete(@RequestBody String id){
        return JsonResult.getSuccessResult(menuJpa.deleteById(id));
    }


}
